package com.achobeta.recruitment.service.impl.wx;

import com.achobeta.recruitment.common.ResultCode;
import com.achobeta.recruitment.dao.wx.WxUserMapper;
import com.achobeta.recruitment.model.SubscribedUser;
import com.achobeta.recruitment.model.WxUser;
import com.achobeta.recruitment.service.student.StudentInfoService;
import com.achobeta.recruitment.service.wx.WxUserService;
import com.achobeta.recruitment.utils.*;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-10-27
 * Time: 21:55
 */
@Service
@Slf4j
public class WxUserServiceImpl implements WxUserService {
    @Value("${wx.appid}")
    private String appId;

    @Value("${wx.secret}")
    private String secret;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private StudentInfoService studentInfoService;

    @Override
    public WxUser getSignUpUserInfo(String code) {
        //根据code获取Access_token的地址
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" + HttpUtils.getQueryString(new HashMap<String, Object>() {{
            this.put("appid", appId);
            this.put("secret", secret);
            this.put("code", code);
            this.put("grant_type", "authorization_code");
        }});
        // 发送请求，接受响应，解析响应
        String result = HttpUtils.doGet(url);
        CheckUtils.checkResult(result, ResultCode.FAILED_UNAUTHORIZED);
        // 拼接url
        String accessToken = JSONObject.parseObject(result).getString("access_token");
        String openId = JSONObject.parseObject(result).getString("openid");
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo" + HttpUtils.getQueryString(new HashMap<String, Object>() {{
            this.put("access_token", accessToken);
            this.put("openid", openId);
            this.put("lang", "zh_CN");
        }});
        // 拉取用户信息
        String userInfo = HttpUtils.doGet(userInfoUrl);
        CheckUtils.checkResult(userInfo, ResultCode.FAILED_UNAUTHORIZED);
        System.out.println(userInfo);
        // 解析
        SubscribedUser user = JsonUtils.jsonToObject(userInfo, SubscribedUser.class);
        // 存入微信号昵称对应表
//        WxUser wxUser = BeanCopyUtils.copyBean(user, WxUser.class);
        WxUser wxUser = new WxUser();
        wxUser.setWxPhoto(user.getHeadimgurl());
        wxUser.setOpenid(user.getOpenid());
        wxUser.setWxName(user.getNickname());
        wxUser.setCreateTime(new Date());
        wxUser.setUpdateTime(new Date());
        wxUser.setDeleteState((byte) 0);
        System.out.println(wxUser);
        WxUser wxUserCheck = wxUserMapper.selectByPrimaryKey(wxUser.getOpenid());
        int rows = 0;
        if(wxUserCheck == null) {
            rows = wxUserMapper.insertSelective(wxUser);
            studentInfoService.initStudentInfo(wxUser.getOpenid());
        }else {
            wxUser.setCreateTime(null);
            rows = wxUserMapper.updateByPrimaryKeySelective(wxUser);
        }
        // 校验
        CheckUtils.checkRows(rows, 1, ResultCode.FAILED_CREATE);
        return wxUser;
    }

    @Override
    public WxUser selectWxUserByOpenid(String openid) {
        // 校验
        CheckUtils.checkStringParams(ResultCode.FAILED_PARAMS_OPENID, openid);
        // 查询
        WxUser wxUser = wxUserMapper.selectByPrimaryKey(openid);
        // 直接返回
        return wxUser;
    }


}
